package com.eenie.common.base

import android.annotation.SuppressLint
import android.app.Application
import android.util.Log
import androidx.annotation.CallSuper
import androidx.lifecycle.ProcessLifecycleOwner
import co.zsmb.rainbowcake.dagger.RainbowCakeComponent
import co.zsmb.rainbowcake.dagger.getViewModelFromFactory
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import com.eenie.common.life.ApplicationLifecycleObserver
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import com.tencent.smtt.sdk.QbSdk
import io.reactivex.Observable
import java.util.concurrent.TimeUnit


abstract class BaseApplication : Application(), QbSdk.PreInitCallback, ApplicationLifecycleObserver {


    /**
     * The injector used by the [getViewModelFromFactory] methods.
     */
    public abstract val injector: RainbowCakeComponent?
    private var isRunning = false

    @CallSuper
    @SuppressLint("CheckResult")
    override fun onCreate() {
        super.onCreate()
        Logger.addLogAdapter(AndroidLogAdapter())
        QbSdk.initX5Environment(applicationContext, this)
        MMKV.initialize(this)
        setupInjector()
        Utils.init(this)
        Observable.just(true)
                .delay(2, TimeUnit.SECONDS)
                .subscribe { res -> isRunning = res }




        ProcessLifecycleOwner.get().lifecycle.addObserver(this)

    }


    open fun isRunning(): Boolean {
        return isRunning
    }

    override fun onCoreInitFinished() {

    }

    override fun onViewInitFinished(initRes: Boolean) {
        Log.i("BaseRainbowApp", "x5 initRes: $initRes")
    }

    /**
     * This method should create a Dagger injector set the [injector] property.
     */
    protected abstract fun setupInjector()


    override fun onAppForeground() {
        LogUtils.i("ApplicationObserver: app moved to foreground")
    }

    override fun onAppBackground() {
        LogUtils.i("ApplicationObserver: app moved to baackground")
    }
}